package com.dd.cloud.user.service.admin.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dd.cloud.common.constants.AdminConstants;
import com.dd.cloud.common.enums.ZkExceptionEnum;
import com.dd.cloud.common.exception.ZekeException;
import com.dd.cloud.common.interceptor.UserInterceptor;
import com.dd.cloud.common.utils.ObjectUtils;
import com.dd.cloud.common.vo.LoginInfo;
import com.dd.cloud.user.entity.admin.ProblemHelp;
import com.dd.cloud.user.mapper.admin.ProblemHelpMapper;
import com.dd.cloud.user.req.admin.AddProblemHelpReq;
import com.dd.cloud.user.req.admin.GetProblemHelpPageReq;
import com.dd.cloud.user.req.admin.UpdateProblemHelpReq;
import com.dd.cloud.user.service.admin.IProblemHelpService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author czg
 * @since 2022-05-07
 */
@Service
public class ProblemHelpServiceImpl extends ServiceImpl<ProblemHelpMapper, ProblemHelp> implements IProblemHelpService {
    /**
     * 分页查询问题帮助
     *
     * @param req
     * @return
     */
    @Override
    public IPage<ProblemHelp> getProblemPage(GetProblemHelpPageReq req) {
        if (!StringUtils.isBlank(req.getStatus())) {
            req.setStatusStr(req.getStatus().split(","));
        }
        IPage<ProblemHelp> page = req.pagePojo();
        page = getBaseMapper().getProblemPage(page, req);
        return page;
    }

    /**
     * 查询问题帮助
     *
     * @return
     */
    @Override
    public List<ProblemHelp> getProblemList() {
        return getBaseMapper().getProblemList();
    }

    /**
     * 查询问题详情 通过id
     *
     * @param id 问题id
     * @return
     */
    @Override
    public ProblemHelp getProblem(Integer id) {
        ProblemHelp problemHelp = getById(id);
        if (problemHelp == null) {
            throw new ZekeException(400, "问题不存在");
        }
        return problemHelp;
    }

    /**
     * 添加问题帮助内容
     *
     * @param req
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addProblemHelp(AddProblemHelpReq req) {
        LoginInfo loginInfo = UserInterceptor.getLoginUserInfo(LoginInfo.UserType.ADMIN).get();
        QueryWrapper<ProblemHelp> qw = new QueryWrapper<>();
        qw.lambda().eq(ProblemHelp::getTitle, req.getTitle()).ne(ProblemHelp::getStatus, AdminConstants.ProblemHelpStatus.DEL);
        ProblemHelp help = getOne(qw);
        if (help != null) {
            throw new ZekeException(400, "该问题已存在");
        }
        help = new ProblemHelp();
        BeanUtils.copyProperties(req, help);
        help.setCreateDate(LocalDateTime.now());
        help.setCreateId(loginInfo.getId());
        help.setStatus(req.getStatus());
        int sort = cumProblemHelpSort(req.getTypeId(), req.getSort(), null);
        help.setSort(sort);
        boolean i = save(help);
        if (!i) {
            throw new ZekeException(ZkExceptionEnum.ADD_ERROR);
        }
        getBaseMapper().updateProblemHelpReorder(null);
    }

    /**
     * 修改问题帮助
     *
     * @param req
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateProblemHelp(UpdateProblemHelpReq req) {
        ProblemHelp help = getById(req.getId());
        if (help == null) {
            throw new ZekeException(400, "问题帮助不存在");
        }
        if (!req.getTitle().equals(help.getTitle())) {
            //修改了标题
            QueryWrapper<ProblemHelp> qw = new QueryWrapper<>();
            qw.lambda().eq(ProblemHelp::getTitle, req.getTitle()).ne(ProblemHelp::getStatus, AdminConstants.ProblemHelpStatus.DEL);
            ProblemHelp problemHelp = getOne(qw);
            if (problemHelp != null) {
                throw new ZekeException(400, "该问题已存在");
            }
        }
        int sort = cumProblemHelpSort(req.getTypeId(), req.getSort(), help.getSort());
        BeanUtils.copyProperties(req, help);
        help.setSort(sort);
        boolean i = updateById(help);
        if (!i) {
            throw new ZekeException(ZkExceptionEnum.ADD_ERROR);
        }
        getBaseMapper().updateProblemHelpReorder(null);
    }

    /**
     * 修改问题帮助状态
     *
     * @param id
     * @param status
     */
    @Override
    public void updateStatusProblemHelp(Integer id, Integer status) {
        ProblemHelp help = getById(id);
        if (help == null) {
            throw new ZekeException(400, "问题帮助不存在");
        }
        if (!ObjectUtils.refrect(AdminConstants.ProblemHelpStatus.class, status)) {
            throw new ZekeException(ZkExceptionEnum.STATUS_DATA_ERROR);
        }
        if (status.equals(help.getStatus())) {
            return;
        }
        help.setStatus(status);
        boolean i = updateById(help);
        if (!i) {
            throw new ZekeException(ZkExceptionEnum.ADD_ERROR);
        }
    }

    /**
     * 问题帮助重排序
     *
     * @param type    问题类型id
     * @param newSort 新的排序位置
     * @param oldSort 原先的排序位置
     * @return 目标位置
     */
    @Transactional(rollbackFor = Exception.class)
    public int cumProblemHelpSort(Integer type, Integer newSort, Integer oldSort) {
        if (oldSort == null) {
            //没有原位置, 为新增
            //先进行重排序
            getBaseMapper().updateProblemHelpReorder(null);
            if (newSort == null) {
                QueryWrapper<ProblemHelp> qu = new QueryWrapper<>();
//                qu.lambda().eq(ProblemHelp::getTypeId, type).orderByDesc(ProblemHelp::getSort).ne(ProblemHelp::getStatus, AdminConstants.ProblemHelpStatus.DEL).last("limit 1");
                qu.lambda().orderByDesc(ProblemHelp::getSort).ne(ProblemHelp::getStatus, AdminConstants.ProblemHelpStatus.DEL).last("limit 1");
                ProblemHelp content = getOne(qu);
                if (content == null) {
                    return 1;
                }
                return content.getSort() + 1;
            }
            UpdateWrapper<ProblemHelp> uw = new UpdateWrapper<>();
//            uw.lambda().ge(ProblemHelp::getSort, newSort).eq(ProblemHelp::getTypeId, type).ne(ProblemHelp::getStatus, AdminConstants.ProblemHelpStatus.DEL).setSql("`sort` = `sort` + 1");
            uw.lambda().ge(ProblemHelp::getSort, newSort).ne(ProblemHelp::getStatus, AdminConstants.ProblemHelpStatus.DEL).setSql("`sort` = `sort` + 1");
            update(uw);
            return newSort;
        }
        if (newSort.equals(oldSort)) {
            return newSort;
        }
        //有原位置, 为修改, 只用修改两个位置之间的数据即可
        if (newSort > oldSort) {
            //后移
            UpdateWrapper<ProblemHelp> uw = new UpdateWrapper<>();
//            uw.lambda().le(ProblemHelp::getSort, newSort).ge(ProblemHelp::getSort, oldSort).eq(ProblemHelp::getTypeId, type).ne(ProblemHelp::getStatus, AdminConstants.ProblemHelpStatus.DEL).setSql("`sort` = `sort` - 1");
            uw.lambda().le(ProblemHelp::getSort, newSort).ge(ProblemHelp::getSort, oldSort).ne(ProblemHelp::getStatus, AdminConstants.ProblemHelpStatus.DEL).setSql("`sort` = `sort` - 1");
            update(uw);
            return newSort;
        } else {
            //前移
            UpdateWrapper<ProblemHelp> uw = new UpdateWrapper<>();
//            uw.lambda().lt(ProblemHelp::getSort, oldSort).ge(ProblemHelp::getSort, newSort).eq(ProblemHelp::getTypeId, type).ne(ProblemHelp::getStatus, AdminConstants.ProblemHelpStatus.DEL).setSql("`sort` = `sort` + 1");
            uw.lambda().lt(ProblemHelp::getSort, oldSort).ge(ProblemHelp::getSort, newSort).ne(ProblemHelp::getStatus, AdminConstants.ProblemHelpStatus.DEL).setSql("`sort` = `sort` + 1");
            update(uw);
            return newSort;
        }
    }
}
